﻿/****************************************************************************
*                                                                           *
* Copyright (c) Ionescu M. Marius. All rights reserved(2010).               *
*                                                                           *
****************************************************************************/

using System;
using System.Collections;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace CustomControlsNS
{
	/// <summary>
	/// Summary description for CustomMenu
	/// </summary>
	public class CustomMenu2 : CompositeControl
	{
		ArrayList lst = new ArrayList();

		private string GetUserID()
		{
			if (HttpContext.Current.Session["UserID"] == null)
			{
				HttpContext.Current.Session["UserID"] = Tools.GetUserID(System.Threading.Thread.CurrentPrincipal.Identity.Name, "");
			}
			if (HttpContext.Current.Session["UserID"] != null)
			{
				return HttpContext.Current.Session["UserID"].ToString();
			}
			else
			{
				FormsAuthentication.SignOut();
				HttpContext.Current.Response.Redirect(this.Page.Request.Url.ToString());
				return null;
			}
		}

		private DataSet GetDataSetUserGroups()
		{
		    DataSet dsUserGroups;
			dsUserGroups = (DataSet)HttpContext.Current.Session["dsUserGroups"];
			if (dsUserGroups == null||1==1)
			{
                dsUserGroups = Hipocrate.DB.DBConnection.GetData("Groups_Select", new string[] { "@UserID" }, new object[] { GetUserID() }, false);
				HttpContext.Current.Session["dsUserGroups"] = dsUserGroups;
			}
			return dsUserGroups;
		}

		protected override void CreateChildControls()
		{
			SiteMapNode r = SiteMap.RootNode;
			lst = new ArrayList();
			Validate(r, false);
			string s = WriteMenuItems(r, -1);
			if (s == "")
				s = "<span>&nbsp;</span>";
			s = "\n" + s + "\n";

			Literal l = new Literal();
			l.Text = s;
			Controls.Add(l);
		}

		private string GetTabs(int nLevel)
		{
			string s = "\t";
			for (int i = 0; i < nLevel; ++i)
				s += "\t";
			return s;
		}

		private bool HasRights(string strUrl)
		{
			DataSet dsUserGroups = GetDataSetUserGroups();
			if (dsUserGroups == null)
				return false;

			DataView dv1 = new DataView(dsUserGroups.Tables[1]);
			dv1.RowFilter = "'" + strUrl + "' LIKE '%' + PageName + '.aspx%'";
			bool bHasRights = (dv1.Count > 0);
			return bHasRights;
		}

		private void Validate(SiteMapNode r, bool bParentRights)
		{
			foreach (SiteMapNode n in r.ChildNodes)
			{
				bool b = HasRights(n.Url.ToString());
				if (b || bParentRights)
					if (!lst.Contains(n))
						lst.Add(n);
				if (b)
				{
					SiteMapNode p = n.ParentNode;
					while (p != null && p != p.ParentNode)
					{
						if (!lst.Contains(p))
							lst.Add(p);
						p = p.ParentNode;
					}
				}
				Validate(n, b || bParentRights);
			}
		}

		private string WriteMenuItems(SiteMapNode r, int nLevel)
		{
			++nLevel;
			string s = "";
            string doublePoint = "::";
			foreach (SiteMapNode n in r.ChildNodes)
			{
				string strItemText = n.Title;
				string strItemHref = n.Url;

				if (!lst.Contains(n) && !strItemHref.EndsWith("#") && !strItemHref.EndsWith("-"))
					continue;

				if (n.HasChildNodes)
				{
					s += "\n" + GetTabs(nLevel) + "<div class='ExpandingDiv'>";
					s += "\n" + GetTabs(nLevel + 1) + "<span OnClick='OnClick_Expanding(this);' OnMouseOver='DoExpandingOnMouseOver(this);' OnMouseOut='DoExpandingOnMouseOut(this);' style='display: block; padding-left: " + (10 * nLevel) + "px;'>";
                    s += "\n" + GetTabs(nLevel + 2) + "<img src='" + this.Page.Request.ApplicationPath + "/Images/Menus/MenuItem.jpg' border='0'> ";
					s += strItemText;
					s += "\n" + GetTabs(nLevel + 1) + "</span>";
					s += "\n" + GetTabs(nLevel + 1) + "<div>";
					s += WriteMenuItems(n, nLevel);
					s += "\n" + GetTabs(nLevel + 1) + "</div>";
					s += "\n" + GetTabs(nLevel) + "</div>";
				}
				else
				{
					if (strItemHref == "")
						continue;
					else if (strItemHref.EndsWith("#"))
						s += "\n <br/>";
					else if (strItemHref.EndsWith("-"))
						s += "\n <hr />";
					else
					{
						s += "\n" + GetTabs(nLevel) + "<a OnMouseOver='DoDefinitionOnMouseOver(this);' OnMouseOut='DoDefinitionOnMouseOut(this);' class='DefinitionA" + (n == SiteMap.CurrentNode ? "sel" : "") + "' href='" + strItemHref + "' target='_top' style='padding-left: " + (10 * nLevel) + "px; width: 100%;'>";
                        //s += "\n" + GetTabs(nLevel + 1) + "<img src='" + this.Page.Request.ApplicationPath + "/Images/Menus/MenuItem.jpg' border='0'> ";
                        s += doublePoint;
                        s += strItemText;
						s += "\n" + GetTabs(nLevel) + "</a>";
					}
				}
			}

			return s;
		}

		protected override void OnPreRender(EventArgs e)
		{
			AddLinkedStyleSheet(this.Page, "~/Styles/Menu.css");
			ScriptManager.RegisterClientScriptInclude(Page, typeof(Page), "Scripts_CustomMenu_js", Page.ResolveClientUrl("~/Scripts/CustomMenu.js"));

			base.OnPreRender(e);
		}

		public void AddLinkedStyleSheet(Page page, string stylesheet)
		{
			bool bAdded = false;
			foreach (Control c in page.Header.Controls)
				if (c is HtmlLink && ((HtmlLink)c).Href == stylesheet)
				{
					bAdded = true;
					continue;
				}
			if (!bAdded)
			{
				HtmlLink link = new HtmlLink();
				link.Href = stylesheet;
				link.Attributes["rel"] = "stylesheet";
				link.Attributes["type"] = "text/css";

				page.Header.Controls.Add(link);
			}
		}

	}
}
